package com.xiaowen.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowen.organization.entity.Organization;
import com.xiaowen.organization.mapper.OrganizationMapper;
import com.xiaowen.organization.service.OrganizationService;
import com.xiaowen.tool.UserContext;
import com.xiaowen.user.entity.User;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yf-wenhao
 * @since 2024-11-20
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {



    @Override
    public Long getSurplusAmount() {
        User user = UserContext.getUser();
        if (null == user) {
            return 0L;
        }
        Integer orgId = user.getOrgId();
        Organization organization = new Organization();
        if (null == orgId) {
            organization.setOrgName(user.getOrgName());
        } else {
            organization.setId(orgId);
        }
        Organization one = this.getOne(new QueryWrapper<>(organization));
        if (null == one) {
            return 0L;
        }
        return one.getTotalAmount() - one.getUsedAmount();
    }

    @Override
    public void addUsedAmount(int size) {
        User user = UserContext.getUser();
        Integer orgId = user.getOrgId();
        Organization organization = new Organization();
        if (null == orgId) {
            organization.setOrgName(user.getOrgName());
        } else {
            organization.setId(orgId);
        }
        //默认循环5次 防止并发
        for (int i = 0; i < 5; i++) {
            //获取原始数据
            Organization one = this.getOne(new QueryWrapper<>(organization));
            Long usedAmount = one.getUsedAmount();
            Organization update = new Organization();
            update.setId(one.getId());
            update.setUsedAmount(usedAmount + size);

            //更新
            UpdateWrapper<Organization> updateWrapper = new UpdateWrapper<>();
            // 设置更新的字段和值
            updateWrapper.set("used_amount", usedAmount + size)
                    .eq("id", one.getId())
                    .eq("used_amount", usedAmount);
            boolean flag = this.update(updateWrapper);
            if (flag) {
                break;
            }
        }
    }
}
